<template>
  <div style="padding-left: 180px;margin-top: 40px;">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
        <el-col :span="11">
          <el-form-item label="用户名：" prop="userName">
            <el-input v-model="formData.userName" disabled placeholder="默认用户登录用户名" :maxlength="11" show-word-limit
              clearable :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="职 称：" prop="type">
            <el-select v-model="formData.type" placeholder="请选择职称">
              <el-option v-for="dict in dict.type.user_auth_role_type_four" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="审核者名称：" prop="authenticationName">
            <el-input v-model="formData.authenticationName" placeholder="请输入凭证信息名称" clearable
              :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="电子邮箱：">
            <el-input v-model="formData.email" placeholder="请输入电子邮箱" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="联系方式：" prop="tel">
            <el-input v-model="formData.tel" placeholder="请输入联系方式" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="邮政地址：" prop="postalAddress">
            <el-input v-model="formData.postalAddress" placeholder="请输入邮政地址" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="传真地址：" prop="faxAddress">
            <el-input v-model="formData.faxAddress" placeholder="请输入邮政地址" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="审核者凭证：" prop="valiDoctor" required style="width: 480px;">
            <el-upload ref="media" :file-list="mediafileList" drag :limit="1" :action="mediaAction" :auto-upload="true"
              :on-success="uploadContent" :headers="headers" :data="{ folderType: 7 }"
              :before-remove="() => { formData.valiDoctor = false; mediafileList = [] }"
              :before-upload="uploadBeforeUpload">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__text">支持扩展名:.png、jpeg、.jpg，最大10M</div>
              <!-- <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button> -->
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="14">
          <el-form-item label="职称证书：" style="width: 480px;">
            <el-upload ref="job" :file-list="jobfileList" drag :limit="1" :action="mediaAction" :auto-upload="true"
              :on-success="uploadPro" :headers="headers" :data="{ folderType: 7 }" :before-upload="uploadBeforeUpload">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__text">支持扩展名:.png、jpeg、.jpg，最大10M</div>
              <!-- <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button> -->
            </el-upload>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="22">
          <el-form-item label="科普目的：" prop="createPurposes">
            <el-checkbox-group v-model="createPurpose" size="medium">
              <el-checkbox v-for="(item, index) in checkListOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="18">
          <el-form-item size="large" style="text-align: center;">
            <el-button type="primary" @click="submitForm">保存认证信息</el-button>
          </el-form-item>
          <!-- <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item> -->
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import { getScanCodeAuthUrl, authenticationDataUser, systemAuthLists, getInfoByUserId, UpdateDataUser } from '@/api/my'
import { getToken } from "@/utils/auth";
export default {
  dicts: ['user_auth_doctor_rank', 'user_auth_role_type_four'],
  components: {},
  props: [],
  data() {
    return {
      validateFile: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择一个文件'));
        } else {
          callback();
        }
      },
      jobList: [   //职称类别
        {
          "label": "医务从业者",
          "value": "1"
        },
        {
          "label": "其他",
          "value": "2"
        }
      ],
      hospList: [   //职称类别
        {
          "label": "郑州大学第一附属医院",
          "value": "1"
        },
        {
          "label": "洛阳骨科医院",
          "value": "2"
        },
        {
          "label": "郑州市人民医院",
          "value": "3"
        },
      ],
      authMyList: [],
      createPurpose: [],              //科普目的
      authorizedAccountId: undefined,  //授权账号
      formData: {
        valiDoctor: '',   //验证是否上传用
        userName: '',  //用户手机号
        type: undefined,  //类别
        // doctorRank: undefined,    //医生职称
        // hospitalName: undefined,   //所属医院名称
        authenticationName: undefined,  // 姓 名
        // authorizedAccountId: undefined,  //授权账号
        //shortDescription: undefined,     //简 介
        email: undefined,                //电子邮箱
        tel: undefined,                 //联系方式
        faxAddress: null,                //传真
        postalAddress: undefined,       //邮政地址
        createPurposes: [],              //科普目的,为了表单验证
        createPurpose: [],              //科普目的
        proofUrl: '',                     //凭证资料url（多个资料，号分隔）
        titleCertificate: '',             //职称证书
        roleType: 4,                  //认证类型创作者（1：个人认证资料 2：机构认证资料）3：新媒体4：审核者
      },
      headers: {
        Authorization: "Bearer " + getToken()
      },
      rules: {
        userName: [{
          required: true,
          message: '默认用户登录用户名',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        ///^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/; 
        type: [{
          required: true,
          message: '请选择职称',
          trigger: 'blur'
        }],
        authenticationName: [{
          required: true,
          message: '请输入凭证信息名称',
          trigger: 'blur'
        }],
        authorizedAccountId: [],
        shortDescription: [],
        email: [
          {
            required: true,
            message: '电子邮件格式错误',
            trigger: 'blur'
          }, {
            pattern: /^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/,
            message: '电子邮件格式错误',
            trigger: 'blur'
          }
        ],
        media: [
          { required: true, validator: this.validateFile, trigger: 'change' },
        ],
        tel: [{
          required: true,
          message: '请填写联系方式',
          trigger: 'blur'
        },
          //{
          //   pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          //   message: '手机号格式错误',
          //   trigger: 'blur'
          // }
        ],
        postalAddress: [],
        createPurpose: [{
          required: true,
          type: 'array',
          message: '请至少选择一个科普目的',
          trigger: 'change'
        }],
        valiDoctor: [{
          required: true,
          message: '请选择上传审核中凭证',
          trigger: 'change'
        }],
      },
      mediafileList: [],  //凭证上传列表
      jobfileList: [],     //职称上传证书列表
      imgHeader: process.env.VUE_APP_ImgUrlHeader,
      mediaAction: process.env.VUE_APP_BASE_API + "/common/resourceFileUpload",
      // uploadAction: process.env.VUE_APP_BASE_API + "/common/commonFileUpload",
      uploadfileList: [],
      docListOptions: [{
        "label": "医务从业人员",
        "value": "isDoctor"
      }],
      checkListOptions: [{
        "label": "课题管理",
        "value": 1
      }, {
        "label": "公益科普",
        "value": 2
      }, {
        "label": "文化传播",
        "value": 3
      }, {
        "label": "创作协同",
        "value": 4
      }, {
        "label": "健康科普",
        "value": 5
      }, {
        "label": "中医问诊",
        "value": 6
      }],
    }
  },
  computed: {
    imgEndUrl(url) {
      // return 123
      return (url) => {
        //  console.log(url,123);
        // const url = "https://ossapi.169000.net/zyykp/sourceMaterialImg/2024/01/22/hushi_20240122152939A001.jpeg";
        const filenameRegex = /.*\/([^/]*?)$/;
        const match = url.match(filenameRegex);
        if (match) {
          return match[1]
          console.log(match[1]);  // 输出: hushi_20240122152939A001.jpeg  
        } else {
          console.log("没有找到文件名");
          return url
        }
      }
    }
  },
  watch: {},
  async created() {
    //console.log(222);


    // await this.AuthList()
    this.init()
  },
  mounted() { },
  methods: {
    init() {
      // console.log();
      this.getAuthMyList()
      // console.log();

    },
    upFail(err, file, fileList) {
      //上传失败
      //   console.log(err,'llll');
      this.mediafileList = []
      this.$message.error('上传失败，请稍后再重试')
    },
    async getAuthMyList() {
      // if (this.$store.state.user.roles[0] == 'ordinaryUser') {
      //   this.formData.userName = this.$store.state.user.phone  //用户手机号
      //   this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
      //   return
      // }
      let res = await getInfoByUserId(this.$store.state.user.userId)
      //  let r = res.data.map(v =>{
      //       v.createPurpose = Number(v.createPurpose)
      //       return v
      //     })
      if (res.code == 200 && !this.isEmptyObject(res.data) && res.data.roleType == 4) {
        try {
          if (res.data.email) this.formData.email = res.data.email
          if (res.data.postalAddress) this.formData.postalAddress = res.data.postalAddress
          this.formData.proofUrl = res.data.proofUrl
          this.mediafileList = [{ url: this.imgHeader + res.data.proofUrl, name: this.imgEndUrl(res.data.proofUrl) }]
          if (res.data.roleType) this.formData.roleType = res.data.roleType
          if (res.data.faxAddress) this.formData.faxAddress = res.data.faxAddress
          if (res.data.tel) this.formData.tel = res.data.tel
          if (res.data.type) this.formData.type = res.data.type.toString()
          this.formData['userDataId'] = res.data.userDataId
          this.formData.userId = res.data.userId
          this.formData.userName = res.data.userName
          this.formData.authenticationName = res.data.authenticationName
          if (res.data.titleCertificate) this.formData.titleCertificate = res.data.titleCertificate
          if (res.data.titleCertificate) {
            this.jobfileList = [{ url: this.imgHeader + res.data.titleCertificate, name: this.imgEndUrl(res.data.titleCertificate) }]
          }
        } catch (e) {
          console.log(e);
        }

        // this.createPurpose = res.data.createPurpose.split(',')
        // this.createPurpose = this.createPurpose.map(v => Number(v))
        // this.authorizedAccountId = this.authMyList.reduce((pre, value, index) => {
        //   pre.push(value.accountId)
        //   return pre
        // }, [])
        // this.formData.authorizedAccountId =  res.data.authorizedAccountList.map(v=>{
        // })
      } else {
        if (res.data.userDataId) {
          this.formData['userDataId'] = res.data.userDataId
        }
        this.formData.userName = this.$store.state.user.phone  //用户手机号
        this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
      }
      //  console.log(res);
    },
    isEmptyObject(obj) {
      return JSON.stringify(obj) === '{}';
    },
    // async AuthList() {  //授权列表
    //   let res = await systemAuthLists({ userId: this.$store.state.user.userId })
    //   if (res.code == 200) {
    //     this.authMyList = res.rows
    //   }
    //   //console.log(res,'----');
    // },
    async toAuth() {  //新授权
      let res = await getScanCodeAuthUrl(this.$store.state.user.userId)
      window.location.href = res.data;
      // console.log(res);
      // alert(123)
    },
    async save() {
      this.formData.createPurpose = this.createPurpose.join()
      if (this.formData.userDataId !== undefined) {
        let result = await UpdateDataUser(this.formData)
        this.$message.success({
          title: '提示',
          message: '更新认证成功'
        })
        this.$emit('closeDia', { name: 'shenhezhe', isClose: false })
        return
      }
      // console.log(this.formData,'ppp');
      let res = await authenticationDataUser(this.formData)
      if (res.code == 200) {
        this.$message.success({
          title: '提示',
          message: '操作成功，请重新登录，正在退出登录'
        })
        this.mediafileList = []
        this.$emit('closeDia', { name: 'shenhezhe', isClose: false })
        this.$message.success({ title: '提示', message: res.msg })
        // this.$store.dispatch('LogOut').then(() => {
        //     location.href = '/index';
        // })
      }
      // console.log(res,'sdfsdf');
      //this.$refs.media.submit();
    },

    submitForm() {

      if (this.$refs['media'].uploadFiles.length < 1) {
        this.formData.valiDoctor = null
      } else {
        this.formData.valiDoctor = true  //如果上传就赋值，下面会通过验证，然后再清空赋值
      }
      this.$refs['elForm'].validate(valid => {
        if (this.formData.valiDoctor == null) return
        // console.log(123);
        // return
        if (!valid) return
        this.save()
        // TODO 提交表单
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    uploadBeforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
        return false
      }
      return isRightSize && isImage
    },
    submitUpload() {
      this.$refs['upload'].submit()
    },
    uploadContent(response, file, fileList) {  //凭证信息
      this.mediafileList = []
      if (response.code == 200) {
        this.formData.proofUrl = response.data.filePath
        this.mediafileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
        // console.log(this.formData.proofUrl, 'sssss');
        this.$message.success({
          title: '提示',
          message: '上传媒体凭证成功'
        })
      } else {
        this.mediafileList = false
        this.$message.info('上传图片失败，请稍后重试')
      }
      //  console.log(response, 123);
    },
    uploadPro(response, file, fileList) {  //职称证书
      this.jobfileList = []
      if (response.code == 200) {
        this.formData['titleCertificate'] = response.data.filePath
        // console.log(this.formData.proofUrl, 'sssss');
        this.jobfileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
        this.$message.success({
          title: '提示',
          message: '上传职称证书成功'
        })
      } else {
        this.jobfileList = false
        this.$message.info('上传图片失败，请稍后重试')
      }
      //  console.log(response, 123);
    },
    mediaBeforeUpload(file, fileList) {
      //console.log('aaa',file);
      const isJPG = file.type === 'image/jpeg';
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
      }
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      return isRightSize && isImage
      // if (!isJPG) {
      //   this.$message.error('只能上传image/jpeg')
      // }
      // return isRightSize && isJPG
      // console.log(file,fileList,'erwer');
    },
  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 410px;
}

::v-deep .el-upload-dragger {
  width: 410px !important;
}
</style>
